package com.talent.jiwen.home;

import android.content.Context;
import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.abc.live.widget.common.ABCSwitchButton;
import com.alibaba.fastjson.JSON;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.talent.jiwen.IndexActivity;
import com.talent.jiwen.R;
import com.talent.jiwen.base.BaseActivity;
import com.talent.jiwen.http.common.ActivityLifeCycleEvent;
import com.talent.jiwen.http.common.ApiFactory;
import com.talent.jiwen.http.common.HttpUtil;
import com.talent.jiwen.http.common.ProgressSubscriber;
import com.talent.jiwen.http.result.CouponListResult;
import com.talent.jiwen.http.result.SaveOrderResult;
import com.talent.jiwen.http.result.StudentInfoResult;
import com.talent.jiwen.my.CouponSelectActivity;
import com.talent.jiwen.my.RechargeActivity;
import com.talent.jiwen.teacher.CourseFragment;
import com.talent.jiwen.teacher.CourseListFragment;
import com.talent.jiwen.training.data.IdNameBean;
import com.talent.jiwen.ui.widgets.LoadingDialog;
import com.talent.jiwen.ui.widgets.NoEmojiEditText;
import com.talent.jiwen.util.Constant;
import com.talent.jiwen.util.ImageUtil;
import com.talent.jiwen.util.LogUtil;
import com.talent.jiwen.util.MaterialDialogUtil;
import com.talent.jiwen.util.SPConstant;
import com.talent.jiwen.util.SPUtil;
import com.talent.jiwen.util.Validators;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;

public class AddProblemActivity extends BaseActivity {
    @BindView(R.id.contentEt)
    NoEmojiEditText contentEt;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.addIv)
    ImageView addIv;
    @BindView(R.id.selectSubjectLayout)
    RelativeLayout selectSubjectLayout;
    @BindView(R.id.subjectTv)
    TextView subjectTv;
    @BindView(R.id.timeSelectLayout)
    RelativeLayout timeSelectLayout;
    @BindView(R.id.teachTimeTv)
    TextView teachTimeTv;
    @BindView(R.id.inviteLayout)
    RelativeLayout inviteLayout;
    @BindView(R.id.switchBtn)
    ABCSwitchButton switchBtn;
    @BindView(R.id.allTeacherTv)
    TextView allTeacherTv;
    @BindView(R.id.schoolTeacherTv)
    TextView schoolTeacherTv;
    @BindView(R.id.schoolStudentTv)
    TextView schoolStudentTv;
    @BindView(R.id.couponLayout)
    RelativeLayout couponLayout;
    @BindView(R.id.couponTv)
    TextView couponTv;
    @BindView(R.id.attentionTv)
    TextView attentionTv;
    @BindView(R.id.askBtn)
    Button askBtn;

    private LoadingDialog loadingDialog;

    //开课方式
    private static final int TYPE_ONE_BY_ONE = 1;//1对1教学
    private static final int TYPE_MULTI = 2;//多人教学
    private int teachType = TYPE_ONE_BY_ONE;
    //课程时间
    private static final int TEACH_NOW = 1;//现在
    private static final int TEACH_ORDER = 2;//预约
    private String answerTime = "";
    private int teachTimeType = TEACH_NOW;

    //老师类型
    private int requiredTeacherType = 0;//0：全部 1：正规教师 2：实习教师
    private static final int ALL_TEACHER = 0;
    private static final int SCHOOL_TEACHER = 1;
    private static final int SCHOOL_STUDENT = 2;

    private List<LocalMedia> pathList = new ArrayList<>();//选择的照片路径
    private List<String> imgList = new ArrayList<>();//压缩后的图片显示路径

    public static final int MAX_IMG = 3;

    private static final String PARAM_GROUP_ID = "param.group.id";
    private static final String PARAM_COUPON_COUNT = "param.coupon.count";
    private static final String PARAM_APPOINT_TEACHER_ID = "param.appoint.teacher.id";
    private static final String PARAM_HAS_ORDER_NOW = "param.has.order.now";
    private static final String PARAM_ORDER_TYPE = "param.order.type";
    private static final String PARAM_COUPON = "param.coupon";
    private static final String PARAM_QUESTION_CONTENT = "param.question.content";
    private static final String PARAM_QUESTION_IMGS = "param.question.imgs";
    private static final String PARAM_SUBJECT_ID = "param.subject.id";

    public static final int ORDER_TYPE_NORMAL = 0;//正常订单
    public static final int ORDER_TYPE_FREE  = 1;//体验/免费订单
    private int orderType;//订单类型，0：普通订单，1：免单型订单
    private int couponCount;//优惠券数量
    private String groupId;//群组Id
    private String appointTeacherId; //指定老师Id
    private boolean hasOrderNow = false;
    private CouponListResult.Coupon coupon;

    private static final String DEFAULT_TEACH_TIME = "即问";
    private int subjectId;
    private String questionImages = "";

    public static final int REQUEST_CODE_COUPON = 111;//选择优惠券

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_add_problem_new_twice;
    }

    @Override
    public String titleName() {
        return getString(R.string.add_problem);
    }

    @Override
    protected void initData() {

        loadingDialog = new LoadingDialog(AddProblemActivity.this , false , "");

        groupId = getIntent().getStringExtra(PARAM_GROUP_ID);
        couponCount = getIntent().getIntExtra(PARAM_COUPON_COUNT , 0);
        orderType = getIntent().getIntExtra(PARAM_ORDER_TYPE , ORDER_TYPE_NORMAL);
        appointTeacherId = getIntent().getStringExtra(PARAM_APPOINT_TEACHER_ID);
        hasOrderNow = getIntent().getBooleanExtra(PARAM_HAS_ORDER_NOW , false);
        String couponStr = getIntent().getStringExtra(PARAM_COUPON);
        //重新提问的参数
        String questionContent = getIntent().getStringExtra(PARAM_QUESTION_CONTENT);
        questionImages = getIntent().getStringExtra(PARAM_QUESTION_IMGS);
        //问题描述
        if (!Validators.isEmpty(questionContent)){
            contentEt.setText(questionContent);
            contentEt.setSelection(questionContent.length());
        }
        //问题图片
        if (!Validators.isEmpty(questionImages)){
            String[] imgs = questionImages.split(",");
            for (int i = 0 ; i < imgs.length ; i++){
                imgList.add(imgs[i]);
            }
        }

        //学科ID
        subjectId = getIntent().getIntExtra(PARAM_SUBJECT_ID , 0);
        if (subjectId != 0){
            String subjectName = Constant.subjectMap.get(subjectId);
            subjectTv.setText(subjectName);
        }

        //默认回答时间 即问
        teachTimeTv.setText(DEFAULT_TEACH_TIME);

        //优惠券数量
        if (couponCount > 0){
            couponLayout.setVisibility(View.VISIBLE);
            couponTv.setText(couponCount + "张");
        }else{
            couponLayout.setVisibility(View.GONE);
        }

        //提问前是否使用了优惠券，判断订单类型
        if (!Validators.isEmpty(couponStr)){
            coupon = JSON.parseObject(couponStr , CouponListResult.Coupon.class);
            couponTv.setText(coupon.getCouponName());

            orderType = coupon.getDiscountType();//免单
        }else{
            orderType = ORDER_TYPE_NORMAL;
        }

        //判断是否有正在进行中的订单
        if (hasOrderNow){
            attentionTv.setVisibility(View.VISIBLE);
        }else{
            attentionTv.setVisibility(View.GONE);
        }

        //图片
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(new CommonAdapter<String>(AddProblemActivity.this, R.layout.item_add_problem_img_new, imgList) {
            @Override
            protected void convert(ViewHolder holder, String s, final int position) {
                ImageView imgIv = (ImageView) holder.getView(R.id.imgIv);
                ImageUtil.loadCorner4Image(AddProblemActivity.this, s, imgIv);

                imgIv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        ImageUtil.picturePreview(AddProblemActivity.this , position  , pathList);
                    }
                });
            }

        });

        //拼班
        switchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
        switchBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
                if (checked){
//                    if(teachTimeType == TEACH_NOW){
//                        showToast(getString(R.string.order_now_can_not_invite));
//                        switchBtn.setChecked(false);
//                    }else{
//                        couponLayout.setVisibility(View.GONE);
//                        orderType = ORDER_TYPE_NORMAL;
//                    }
//                    couponLayout.setVisibility(View.GONE);

                    couponTv.setText("拼班不可用");
                    couponLayout.setEnabled(false);

                    orderType = ORDER_TYPE_NORMAL;
                    teachType = TYPE_MULTI;
                    if(Validators.isEmpty(answerTime)){
                        teachTimeTv.setText("");
                    }


                }else{
//                    couponLayout.setVisibility(View.VISIBLE);
                    couponLayout.setEnabled(true);

                    teachType = TYPE_ONE_BY_ONE;
                    if (null != coupon){
                        orderType = coupon.getDiscountType();
                        couponTv.setText(coupon.getCouponName());
                    }else{
                        orderType = ORDER_TYPE_NORMAL;
                        couponTv.setText(couponCount + "张");
                    }

                    if (Validators.isEmpty(answerTime)){
                        teachTimeTv.setText(DEFAULT_TEACH_TIME);
                    }
                }
            }
        });

    }

    @OnClick({R.id.timeSelectLayout ,  R.id.addIv, R.id.selectSubjectLayout
            , R.id.askBtn , R.id.couponLayout , R.id.allTeacherTv , R.id.schoolTeacherTv , R.id.schoolStudentTv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.timeSelectLayout:
                showWheelPicker(getTimeList(teachType) , null);
                break;
            case R.id.addIv:
                ImageUtil.pickPhoto(AddProblemActivity.this , MAX_IMG  , pathList , true);
                break;
            case R.id.selectSubjectLayout:
                showSubjectPicker(subjectId);
                break;
            case R.id.askBtn:

//                //判断是否是拼单
//                if(switchBtn.isChecked()){
//                    teachType = TYPE_MULTI;
//                }else{
//                    teachType = TYPE_ONE_BY_ONE;
//                }

                if (subjectId == 0){
                    showToast(getString(R.string.please_select_subject));
                }else if(Validators.isEmpty(contentEt.getText().toString())){
                    if (Validators.isEmpty(questionImages)){
                        if(Validators.isEmpty(imgList)){
                            showToast(getString(R.string.please_add_content));
                        }
                    }
                }else if (teachTimeType == TEACH_ORDER && Validators.isEmpty(answerTime)){
                    showToast(getString(R.string.please_select_teach_time));
                }else{

                    if (teachType == TYPE_ONE_BY_ONE){
                        if (teachTimeType == TEACH_NOW && hasOrderNow){
                            Toast.makeText(this, "您当前有正在进行中的即时订单，不可以再发布即时订单", Toast.LENGTH_LONG).show();
                            return;
                        }
                    }else{
                        if (Validators.isEmpty(answerTime)){
                            showToast("请选择时间");
                            return;
                        }
                    }

                    askProblem();
                }
                break;
            case R.id.couponLayout:
                Intent couponSelectIntent = new Intent();
                couponSelectIntent.setClass(this , CouponSelectActivity.class);
                couponSelectIntent.putExtra(CouponSelectActivity.PARAM_SELECT_COUPON , JSON.toJSONString(coupon));
                startActivityForResult(couponSelectIntent , REQUEST_CODE_COUPON);
                break;
            case R.id.allTeacherTv:
                requiredTeacherType = ALL_TEACHER;

                allTeacherTv.setTextColor(ContextCompat.getColor(this , R.color.common_app_color));
                allTeacherTv.setBackgroundResource(R.drawable.bg_circle_teacher_sel);

                schoolTeacherTv.setTextColor(ContextCompat.getColor(this , R.color.text_gray_6));
                schoolTeacherTv.setBackgroundResource(R.drawable.bg_circle_teacher_nor);

                schoolStudentTv.setTextColor(ContextCompat.getColor(this , R.color.text_gray_6));
                schoolStudentTv.setBackgroundResource(R.drawable.bg_circle_teacher_nor);
                break;
            case R.id.schoolTeacherTv:
                requiredTeacherType = SCHOOL_TEACHER;

                allTeacherTv.setTextColor(ContextCompat.getColor(this , R.color.text_gray_6));
                allTeacherTv.setBackgroundResource(R.drawable.bg_circle_teacher_nor);

                schoolTeacherTv.setTextColor(ContextCompat.getColor(this , R.color.common_app_color));
                schoolTeacherTv.setBackgroundResource(R.drawable.bg_circle_teacher_sel);

                schoolStudentTv.setTextColor(ContextCompat.getColor(this , R.color.text_gray_6));
                schoolStudentTv.setBackgroundResource(R.drawable.bg_circle_teacher_nor);
                break;
            case R.id.schoolStudentTv:
                requiredTeacherType = SCHOOL_STUDENT;

                allTeacherTv.setTextColor(ContextCompat.getColor(this , R.color.text_gray_6));
                allTeacherTv.setBackgroundResource(R.drawable.bg_circle_teacher_nor);

                schoolTeacherTv.setTextColor(ContextCompat.getColor(this , R.color.text_gray_6));
                schoolTeacherTv.setBackgroundResource(R.drawable.bg_circle_teacher_nor);

                schoolStudentTv.setTextColor(ContextCompat.getColor(this , R.color.common_app_color));
                schoolStudentTv.setBackgroundResource(R.drawable.bg_circle_teacher_sel);

                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        PictureFileUtils.deleteCacheDirFile(AddProblemActivity.this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:

                    pathList.clear();
                    pathList.addAll(PictureSelector.obtainMultipleResult(data));

                    if(!Validators.isEmpty(pathList)){
                        questionImages = "";
                    }

                    if (Validators.isEmpty(questionImages)){
                        imgList.clear();
                        for (LocalMedia localMedia : pathList) {
                            imgList.add(localMedia.getCompressPath());
                        }

                        recyclerView.getAdapter().notifyDataSetChanged();

                        if (imgList.size() == 3){
                            addIv.setVisibility(View.GONE);
                        }else{
                            addIv.setVisibility(View.VISIBLE);
                        }
                    }


                    break;
                case REQUEST_CODE_COUPON:
                    String couponResultStr = data.getStringExtra(CouponSelectActivity.PARAM_COUPON_RESULT);

                    if (!Validators.isEmpty(couponResultStr)){
                        coupon = JSON.parseObject(data.getStringExtra(CouponSelectActivity.PARAM_COUPON_RESULT) , CouponListResult.Coupon.class);

                        orderType = coupon.getDiscountType();
                        couponTv.setText(coupon.getCouponName());
                    }else{
                        coupon = null;

                        orderType = ORDER_TYPE_NORMAL;
                        couponTv.setText( couponCount + "张");
                    }

                    break;
            }
        }
    }

    /**提问
     *
     */
    private void askProblem(){

        if (orderType == ORDER_TYPE_NORMAL){
            //获取学生账户余额比对，如果少于60元,提示去充值,
            Map<String, String> map = new HashMap<>();
            map.put("studentId" , SPUtil.stringOut(SPConstant.USER_ID));
            Observable observable = ApiFactory.getEducationApiSingleton().getStudentSelfInfo(SPUtil.stringOut(SPConstant.TOKEN) , map);
            HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<StudentInfoResult>(this) {
                @Override
                protected void _onNext(StudentInfoResult studentInfoResult) {
                    String amount = studentInfoResult.getStudentInfo().getTotalMoney();
                    if (!Validators.isEmpty(amount)){
                        try {
                            double totalMoney = Double.parseDouble(amount);
                            if (totalMoney < 60){
                                MaterialDialogUtil.getCommonDialog(AddProblemActivity.this, "提示", "您的账户余额不够支付本次提问，请充值后再提问！"
                                        , "确定", "取消"
                                        , new MaterialDialogUtil.OnDialogPoNeClickListener() {
                                            @Override
                                            public void onPositive() {
                                                intentActivity(RechargeActivity.class);
                                            }

                                            @Override
                                            public void onNegative() {

                                            }
                                        }).show();
                            }else{
                                loadingDialog.show();
                                if (needUploadImg()){
                                    uploadPic();
                                }else{
                                    saveOrderInfo();
                                }
                            }
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                protected void _onError(String message) {
                    showToast(message);
                }
            }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject,false);

        }else{
            loadingDialog.show();
            if (needUploadImg()){
                uploadPic();
            }else{
                saveOrderInfo();
            }
        }

    }

    /**是否需要上传图片
     *
     * @return
     */
    private boolean needUploadImg(){
//        !Validators.isEmpty(imgList)
        if (!Validators.isEmpty(questionImages)){
            return false;
        }else{
            if (Validators.isEmpty(imgList)){
                return false;
            }else{
                return true;
            }
        }
    }
    /**学科选择
     *
     * @param selectedSubjectId
     */
    private void showSubjectPicker(final int selectedSubjectId) {
        final List<IdNameBean> subjectList = new ArrayList<>();
        for (Map.Entry<Integer, String> entry : Constant.subjectMap.entrySet()) {
            IdNameBean bean = new IdNameBean(entry.getKey() ,entry.getValue());
            subjectList.add(bean);
        }

        List<String> showList = new ArrayList<>();
        int selectPosition = 0;
        for (int i = 0; i < subjectList.size(); i++) {
            showList.add(subjectList.get(i).getName());
            if (selectedSubjectId == subjectList.get(i).getId()) {
                selectPosition = i;
            }
        }
        OptionsPickerView pvOptions = new OptionsPickerBuilder(AddProblemActivity.this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                subjectId = subjectList.get(options1).getId();
                subjectTv.setText(subjectList.get(options1).getName());
            }
        }).setSubmitColor(ContextCompat.getColor(this , R.color.common_app_color))
                .setCancelColor(ContextCompat.getColor(this , R.color.text_gray_6)).build();
        pvOptions.setPicker(showList);

        if (selectedSubjectId != 0) {
            pvOptions.setSelectOptions(selectPosition);
        }
        pvOptions.show();
    }

    /**
     * 滚轮选择
     *
     * @param pickerList
     * @param selectItem
     */
    private void showWheelPicker(final List<IdNameBean> pickerList, final IdNameBean selectItem) {
        List<String> showList = new ArrayList<>();
        int selectPosition = 0;
        for (int i = 0; i < pickerList.size(); i++) {
            showList.add(pickerList.get(i).getName());
            if (null != selectItem){
                if (selectItem.getIdStr().equals(pickerList.get(i).getIdStr())) {
                    selectPosition = i;
                }
            }
        }
        OptionsPickerView pvOptions = new OptionsPickerBuilder(AddProblemActivity.this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                teachTimeTv.setText(pickerList.get(options1).getName());
                answerTime = pickerList.get(options1).getIdStr();

                if(Validators.isEmpty(answerTime)){

                    //立即问的都是设置为不拼单
                    teachTimeType = TEACH_NOW;

                    switchBtn.setChecked(false);

                }else{
                    teachTimeType = TEACH_ORDER;
                }

            }
        }).setSubmitColor(ContextCompat.getColor(this , R.color.common_app_color))
                .setCancelColor(ContextCompat.getColor(this , R.color.text_gray_6)).build();
        pvOptions.setPicker(showList);

        if (null != selectItem) {
            pvOptions.setSelectOptions(selectPosition);
        }
        pvOptions.show();
    }

    /**获取距现在某一小时的时刻
     *
     * @return
     */
    public static List<IdNameBean> getTimeList(int type){
        List<IdNameBean> timeList = new ArrayList<>();
        if (type == TYPE_ONE_BY_ONE){
            //添加第一个即时
            IdNameBean nowNameBean = new IdNameBean();
            nowNameBean.setIdStr("");
            nowNameBean.setName(DEFAULT_TEACH_TIME);
            timeList.add(nowNameBean);
        }

        SimpleDateFormat df = new SimpleDateFormat("MM月dd日 HH点mm分");
        Calendar c = Calendar.getInstance(); // 当时的日期和时间
        int orginalDay = c.get(Calendar.DAY_OF_YEAR);

        int min = c.get(Calendar.MINUTE);
        if (min < 15){
            c.set(Calendar.MINUTE, 15);
        }else if (min > 15 && min < 30){
            c.set(Calendar.MINUTE, 30);
        }else if (min > 30 && min < 45){
            c.set(Calendar.MINUTE, 45);
        }else{
            c.set(Calendar.HOUR , c.get(Calendar.HOUR) + 1);
            c.set(Calendar.MINUTE , 0);
        }

        c.set(Calendar.MINUTE , c.get(Calendar.MINUTE) + 15);

        IdNameBean idNameBean = new IdNameBean();
        idNameBean.setIdStr(String.valueOf(c.getTime().getTime()));
        idNameBean.setName(df.format(c.getTime()));
        timeList.add(idNameBean);

        boolean add = true;
        while (add){
            int currentDay = c.get(Calendar.DAY_OF_YEAR);
            if (orginalDay == currentDay){
                c.set(Calendar.MINUTE, c.get(Calendar.MINUTE) + 15);

                IdNameBean data = new IdNameBean();
                data.setIdStr(String.valueOf(c.getTime().getTime()));
                data.setName(df.format(c.getTime()));

                timeList.add(data);

            }else{
                add = false;
            }
        }
        return timeList;
    }

    /**上传图片并保存
     *
     */
    private void uploadPic(){

        ImageUtil.upLoadImgs(imgList, new ImageUtil.ImgUpLoadListener() {
            @Override
            public void OnSuccess(String successUrl) {

            }

            @Override
            public void OnError(String message) {
            }

            @Override
            public void OnListUpSuccess(List<String> successFileList) {
                questionImages = Constant.listToString(successFileList);
                LogUtil.e("图片地址"  , questionImages);
                saveOrderInfo();
            }
        });
    }

    /**保存订单信息
     *
     */
    private void saveOrderInfo(){
        Map<String, String> map = new HashMap<>();
        map.put("creatorId" , SPUtil.stringOut(SPConstant.USER_ID));
        map.put("questionIntroduction" , contentEt.getText().toString());
        map.put("questionImages" , questionImages);
        //回答方式，即时，预约
        map.put("answerType" , teachTimeType + "");
        if (teachTimeType == TEACH_ORDER){
            map.put("answerTime" , answerTime);
        }
        map.put("gradeLevel" , SPUtil.intOut(SPConstant.SELECT_GRADE) + "");//年级
        map.put("subjectId" , subjectId + "");//学科
        map.put("groupId" , groupId);//群组
        map.put("teachingType" , teachType + "");//群组

        map.put("requiredTeacherType" , requiredTeacherType + "");//老师类型
        //如果有指定教师就传指定教师
        if (!Validators.isEmpty(appointTeacherId)){
            map.put("appointTeacherId" , appointTeacherId);
        }

        map.put("orderType" , orderType + "");
        //普通订单不传优惠券
        if (orderType != ORDER_TYPE_NORMAL){
            if (null != coupon){
                map.put("couponId" , coupon.getId() + "");
            }else{
                map.put("couponId" , "");
            }
        }


        Observable observable = ApiFactory.getEducationApiSingleton().saveOrderInfo(SPUtil.stringOut(SPConstant.TOKEN) , map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<SaveOrderResult>(this) {
            @Override
            protected void _onNext(SaveOrderResult saveOrderResult) {
                loadingDialog.dismiss();
                String orderId  = saveOrderResult.getOrderId();
                if (teachType == TYPE_ONE_BY_ONE){
                    IndexActivity.tab2checked = true;
                    CourseFragment.fragment1Checked =true;

                    EventBus.getDefault().post(CourseListFragment.REFRESH_COURSE_LIST);
                    finish();
                }else{
                    TogetherListActivity.startTogetherActivity(AddProblemActivity.this , answerTime , System.currentTimeMillis(),  groupId , orderId);
                    finish();
                }
            }

            @Override
            protected void _onError(String message) {
                loadingDialog.dismiss();
                showToast(message);
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject,false);
    }

    /**启动该页面
     *
     * @param context
     * @param groupId 群组Id
     * @param couponCount 优惠券数量
     * @param hasOrderNow 是否有进行中的订单
     * @param couponStr 从优惠券列表进入的使用的优惠券数据
     * @param appointTeacherId 从收藏列表进入的指定老师的Id
     */
    public static void startAddProblemActivity(Context context , String groupId, int couponCount , boolean hasOrderNow
            , String couponStr , String appointTeacherId){
//        Intent intent = new Intent();
//        intent.setClass(context , AddProblemActivity.class);
//        intent.putExtra(PARAM_GROUP_ID , groupId);
//        intent.putExtra(PARAM_COUPON_COUNT , couponCount);
//        intent.putExtra(PARAM_APPOINT_TEACHER_ID , appointTeacherId);
//        intent.putExtra(PARAM_HAS_ORDER_NOW , hasOrderNow);
//        intent.putExtra(PARAM_COUPON , couponStr);
//
//        context.startActivity(intent);
        startAddProblemActivity(context , groupId , couponCount , hasOrderNow , couponStr , appointTeacherId , "" , ""  ,0);
    }


    public static void startAddProblemActivity(Context context , String groupId, int couponCount , boolean hasOrderNow
            , String couponStr , String appointTeacherId  , String content , String imgs , int subjectId){
        Intent intent = new Intent();
        intent.setClass(context , AddProblemActivity.class);
        intent.putExtra(PARAM_GROUP_ID , groupId);
        intent.putExtra(PARAM_COUPON_COUNT , couponCount);
        intent.putExtra(PARAM_APPOINT_TEACHER_ID , appointTeacherId);
        intent.putExtra(PARAM_HAS_ORDER_NOW , hasOrderNow);
        intent.putExtra(PARAM_COUPON , couponStr);
        intent.putExtra(PARAM_QUESTION_CONTENT , content);
        intent.putExtra(PARAM_QUESTION_IMGS , imgs);
        intent.putExtra(PARAM_SUBJECT_ID , subjectId);

        context.startActivity(intent);
    }
}
